local cjson = require "cjson"
ngx.req.read_body()
local messageUri = ngx.var.uri
local data = ngx.req.get_body_data() or ""
ngx.var.mumuYuyinKey = data                          --跟body_filter进行数据交互
local function getIp()
    local myIP = ngx.req.get_headers()["X-Real-IP"]
    if myIP == nil then
        myIP = ngx.req.get_headers()["x_forwarded_for"]
    end
    if myIP == nil then
        myIP = ngx.var.remote_addr
    end
    return myIP;
end

local function dict_safe_incr(dict, metric, value, exptime)
    if tonumber(value) == nil then
        return
    end

    local newval, err = dict:incr(metric, value)
    if not newval and err == "not found" then
        local ok, err = dict:safe_add(metric, value, exptime)
        if err == "exists" then
            dict:incr(metric, value)
        elseif err == "no memory" then
            ngx.log(ngx.ERR, "no memory for nginx_metric add kv: " .. metric .. ":" .. value)
        end
    end

    --if newval>10 then
    --
    --end
end

--local cache_list = ngx.shared.cache_list
--local  cache_url= cache_list:get(ngx.var.uri)  or ""
--
--dict_safe_incr(cache_list,ngx.var.uri.."_count",1,120)
--ngx.log(ngx.ERR,"第一次:cache_url_count"..ngx.var.uri  .." "..cache_list:get(ngx.var.uri.."_count"))

local key = "limit:ip:blacklist"
local ip = getIp();
local shared_ip_blacklist = ngx.shared.shared_ip_blacklist

--获得本地缓存的最新刷新时间
local last_update_time = shared_ip_blacklist:get("last_update_time");

if last_update_time ~= nil then
    local dif_time = ngx.now() - last_update_time
    if dif_time < 60 then --缓存1分钟,没有过期
        if shared_ip_blacklist:get(ip) then
            local reponseJson =  ' {\"code\":901,\"data\":null,\"detail\":\"\"ip地址在黑名单,\"msg\":\"\"} '
            ngx.say(reponseJson)
            ngx.exit(ngx.status)
            ngx.log(ngx.ERR, "shared_ip_blacklist 拦截ip".. ip)
         --   return ngx.exit(ngx.HTTP_FORBIDDEN) --直接返回403
        end
        --ngx.log(ngx.ERR, "正常用户")
       -- return
    end
end


local redis = require "lib.redis"  --引入redis模块
local red = redis:new()



if shared_ip_blacklist:get(ip) then
    ngx.log(ngx.ERR, "ip已经封锁")
    local reponseJson =  ' {\"code\":901,\"data\":null,\"detail\":\"\"ip地址在黑名单,\"msg\":\"连。\"} '
    ngx.say(reponseJson)
    ngx.exit(ngx.status)
   -- return ngx.exit(ngx.HTTP_FORBIDDEN) --直接返回403
end
local cache_list = ngx.shared.cache_list
--local keys = cache_list:get_keys(1000)  -- 一秒处理 50 个数据
--
--for index, key in pairs(keys) do
--    str = ((nil ~= str) and str..[[#]]..cache_list:get(key)) or cache_list:get(key)
--    ngx.log(ngx.ERR,"key="..key.." str=" ..str)
--   -- ngx_share:delete(key)  --干掉这个 key
--end
local current_url= ngx.var.uri
local  cache_url= cache_list:get(current_url)  or ""

if not (cache_url == "") then
    local key_url=current_url.."_current"
    local cache_json = cjson.decode(cache_url)
    dict_safe_incr(cache_list,key_url,1,cache_json["limit_time"])

    local limit_current= cache_list:get(key_url) or ""
    --ngx.log(ngx.ERR,"第二次cache_url_count"..ngx.var.uri  .." "
    --        ..cache_list:get(key_url)
    --        .. cache_list:get(current_url).."=..cache_url")


    if not (limit_current == "") then

        if tonumber(limit_current)  then


                --ngx.log(ngx.ERR,"key_url===" ..key_url.." ngx.var.uri="..cache_url)
                --ngx.log(ngx.ERR,"limit_current===" ..limit_current.." limit_max="..cache_json["limit_max"])

                if (tonumber(limit_current)>tonumber(cache_json["limit_max"])) then
                    ngx.log(ngx.ERR,"key_url===" ..key_url.." ngx.var.uri="..cache_url)
                    local reponseJson =  ' {\"code\":901,\"data\":null,\"detail\":\"\"url地址已经限流,\"msg\":\"连。\"} '
                    ngx.say(reponseJson)
                    ngx.exit(ngx.status)
                end


        end
    end

end
local current_url= ngx.var.uri
local  cache_url= cache_list:get(current_url)  or ""

if not (cache_url == "") then
    local  cache_data=cache_list:get(current_url..ngx.var.mumuYuyinKey..'data') or ""
    if not (cache_data == "") then
             ngx.log(ngx.ERR, current_url..ngx.var.mumuYuyinKey.."  ")
            ngx.say(cache_data )
            ngx.exit(ngx.status)
            return


    end
end

redis:close_redis(red)

